<template>
  <div>
    <form class="studentForm">
      <!-- v-model 双向绑定数据 -->
      <input v-model="stuFormData.id" type="hidden" class="studentIdToEdit" />
      <label for="studentName">Name</label>
      <input v-model="stuFormData.name" type="text" name="name" class="studentName" required />
      <label for="studentGender">Gender</label>
      <select v-model="stuFormData.gender" name="gender" class="studentGender" required>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>
      <label for="studentHobbies">Hobbies</label>
      <input
        v-model="stuFormData.hobbies"
        type="text"
        name="hobbies"
        class="studentHobbies"
        required
      />
      <label for="studentEmail">Email</label>
      <input v-model="stuFormData.email" type="email" name="email" class="studentEmail" required />
      <label for="studentPhone">Phone</label>
      <input v-model="stuFormData.phone" type="text" name="phone" class="studentPhone" required />
      <label for="studentAge">Age</label>
      <input v-model="stuFormData.age" type="number" name="age" class="studentAge" required />
      <button @click.prevent="saveStuInfo" type="submit" class="saveStudentBtn">保存信息</button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { log } from 'echarts/types/src/util/log.js'
import { ref, toValue, watch } from 'vue'

// 定义数据类型（建议将接口类型写在组件中，父组件导入使用）
export interface IStudent {
  id: string
  name: string
  gender: string
  hobbies: string
  email: string
  phone: string
  age: number | string
  create_at?: string
  update_at?: string
  selected?: boolean // 实现复选框
}

const { userInfo } = defineProps<{
  userInfo: IStudent
}>()

// const stuFormData = ref<IStudent>()   可能为undefined，因此全变成可选
type PIStudent = Partial<IStudent>
// const stuFormData = ref<PIStudent>({})
// 初次赋值
const stuFormData = ref<PIStudent>(userInfo)

const emit = defineEmits<{
  (e: 'save', userInfoForm: IStudent): void
}>()

const saveStuInfo = () => {
  emit('save', stuFormData.value as IStudent)
}

// 通过watch监听获取值，一监听到更新就赋值
watch(
  () => toValue(userInfo),
  () => {
    stuFormData.value = userInfo
    console.log(userInfo, 'userInfo')
  }
)

// 报错："userInfo" is a destructured prop and should not be passed directly to watch(). Pass a getter () => userInfo instead
// 解析：因为监听的userInfo是状态变量，当该对象完全改变时会丢失引用，从而监听不到，此时应用getter包装
// watch(userInfo, () => {
//   console.log(userInfo, 'userInfo')
// })
</script>

<style scoped>
label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input,
select {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.saveStudentBtn {
  background-color: #4caf50;
  color: #fff;
  padding: 10px;
  font-size: 16px;
  border-radius: 4px;
  width: 100%;

  &:hover {
    background-color: #45a049;
  }
}
</style>
